package com.dbsop.domain.transport.query;

import com.dbsop.domain.AbsConditionQuery;
import com.dbsop.domain.SubCondition;
import com.dbsop.common.enums.FlagConnect;
import com.dbsop.domain.transport.res.TransportUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * 条件查询
 */
public abstract class ConditionQuery  extends AbsConditionQuery {

    /**
     * 列名
     */
    private String columnName;

    /**
     * 连接符
     */
    private FlagConnect flagConnect = FlagConnect.AND;

    private FlagConnect subConnect = FlagConnect.AND;

    private List<SubCondition> subConditions = new ArrayList<SubCondition>();

    public ConditionQuery(String columnName) {
        this.columnName = columnName;
    }

    public ConditionQuery(String columnName, FlagConnect flagConnect) {
        this.columnName = columnName;
        this.flagConnect = flagConnect;
    }


    public QueryBuilder getSubQueryBuilder(){
        BoolQueryBuilder subQueryBuilder = null;
        FlagConnect subConnect= null;
        if (subConditions.size() == 0) return null;

        for (SubCondition subCondition : subConditions) {
            List<AbsConditionQuery> subQueries = subCondition.getSubQueries();
            if (subQueries.size() == 0)continue;
            BoolQueryBuilder subBoolQueryBuilder = TransportUtils.subBoolQueryBuilder(subQueries);
            if (subQueryBuilder == null){
                subQueryBuilder = subBoolQueryBuilder;
                subConnect = subCondition.getSubConnect();
            }else {
                BoolQueryBuilder newBool = new BoolQueryBuilder();
                TransportUtils.flagConnectHandler(subConnect,newBool,subQueryBuilder,subBoolQueryBuilder);
                subQueryBuilder = newBool;
                subConnect = subCondition.getSubConnect();
            }
        }
        return subQueryBuilder;
    }
    /**
     * 转换条件
     * @return
     */
    public QueryBuilder paringBoolQuery(){
        return extractBoolQuery();
    }

    public abstract QueryBuilder extractBoolQuery();

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public FlagConnect getFlagConnect() {
        return flagConnect;
    }

    public void setFlagConnect(FlagConnect flagConnect) {
        this.flagConnect = flagConnect;
    }


    public List<SubCondition> getSubConditions() {
        return subConditions;
    }

    public void setSubConditions(List<SubCondition> subConditions) {
        this.subConditions = subConditions;
    }


    public FlagConnect getSubConnect() {
        return subConnect;
    }

    public void setSubConnect(FlagConnect subConnect) {
        this.subConnect = subConnect;
    }
}
